package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.redis.cache.SpzxCache;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.SkuQuery;
import com.spzx.product.api.domain.vo.SkuPriceVo;
import com.spzx.product.api.domain.vo.SkuStockVo;
import com.spzx.product.api.domain.Product;
import com.spzx.product.api.domain.ProductDetails;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2024-10-26
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    private ProductSkuService productSkuService;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private SkuStockService skuStockService;

    @Autowired
    private ProductDetailsService productDetailsService;

    @Autowired
    private ProductDetailsMapper productDetailsMapper;

    @Autowired
    private SkuStockMapper skuStockMapper;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public List<Product> getPageList(Product product) {
        return baseMapper.getPageList(product);
    }

    @Override
    public boolean saveProduct(Product product) {
        //调用自带的方法保存商品信息
        baseMapper.insert(product);

        //根据product对象获取sku的信息
        List<ProductSku> productSkuList = product.getProductSkuList();

        //空集合,用于保存遍历出sku集合的数据
        List<ProductSku> products = new ArrayList<>();


        //遍历集合productSkuList
        for (int i = 0; i < productSkuList.size(); i++) {
            //获取productSku 对象
            ProductSku productSku = productSkuList.get(i);
            //获取商品id
            Long productId= product.getId();
            //设置商品id
             productSku.setProductId(productId);
            //设置productSku中sku_code的id//设置sku_code
            productSku.setSkuCode(productId+"_"+i);
            //设置sku_name
            productSku.setSkuName(product.getName()+"__"+productSku.getSkuSpec());
            //设置状态值
            productSku.setStatus(0);
            //把productSku添加到products集合中
            products.add(productSku);
        }
        //批量保存
        productSkuService.saveBatch(products);

        List<SkuStock> stocks=new ArrayList<>();
        for (int i = 0; i < products.size(); i++) {
            //获取ProductSku
            ProductSku productSku = products.get(i);
            //创建skuStock对象
            SkuStock skuStock = new SkuStock();
            skuStock.setSkuId(productSku.getId());
            skuStock.setStatus(0);

            //获取商品的库存
            Integer stockNum = productSku.getStockNum();
            skuStock.setAvailableNum(stockNum);
            skuStock.setTotalNum(stockNum);
            skuStock.setLockNum(0);
            stocks.add(skuStock);
        }

        skuStockService.saveBatch(stocks);
        //获取商品图片信息
        List<String> detailsImageUrlList = product.getDetailsImageUrlList();
        String detailsImageUrl = String.join(",", detailsImageUrlList);

        ProductDetails productDetails = new ProductDetails();
        productDetails.setProductId(product.getId());
        productDetails.setImageUrls(detailsImageUrl);


        productDetailsService.save(productDetails);

        return true;
    }

    @Override
    public Product getProductById(Long id) {
        //根据id查询商品信息
        Product product = getById(id);

        //根据商品id查询SKU信息
        List<ProductSku> productSkuList = productSkuService.list(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
        product.setProductSkuList(productSkuList);
        //遍历productSkuList获取sku_id
        productSkuList.forEach(productSku -> {
            SkuStock stock = skuStockService.getOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, productSku.getId()));
            productSku.setStockNum(stock.getTotalNum());
        });
        //根据商品id查询图片信息
        ProductDetails productDetails = productDetailsService.getOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
        //获取图片的详细地址
        String imageUrls = productDetails.getImageUrls();
        //字符串切割成数组
        String[] split = imageUrls.split(",");
        //数组转换为集合
        List<String> list = Arrays.asList(split);
        product.setDetailsImageUrlList(list);

        return product;
    }

    @Override
    public boolean saveProductById(Product product) {
        //调用自带的方法更新商品信息
        baseMapper.updateById(product);


        //获取productSkuList集合
        List<ProductSku> productSkuList = product.getProductSkuList();

        productSkuList.forEach(productSku -> {
            //获取商品sku的id
            Long skuId = productSku.getId();
            //根据sku的id获取sku对象
            SkuStock skuStock = skuStockService.getOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId,skuId));

            //设置更新日期
            skuStock.setUpdateTime(new Date());

            //设置总库存和可用库存
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setAvailableNum(productSku.getStockNum()-skuStock.getLockNum());

            skuStockService.updateById(skuStock);
        });
        //获取传过来的商品图片信息详细地址的集合
        List<String> detailsImageUrlList = product.getDetailsImageUrlList();
        //集合转字符串
        String detailsImageUrls = String.join(",", detailsImageUrlList);
        //根据商品id查询商品图片信息
        ProductDetails productDetails = productDetailsService.getOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, product.getId()));
        //设置更新日期
        productDetails.setUpdateTime(new Date());
        //更新地址
        productDetails.setImageUrls(detailsImageUrls);
        //更新数据库
        productDetailsMapper.updateById(productDetails);

        return true;
    }

    @Override
    public void deleteProductById(List<Long> ids) {
        //调用自己的方法删除商品信息
        baseMapper.deleteBatchIds(ids);

        //获取所有的商品sku
        List<ProductSku> productSkuList = productSkuService.list(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getProductId, ids));

        productSkuList.forEach(productSku -> {
            //删除sku信息
            productSkuService.removeById(productSku.getId());
            //根据sku的id删除库存信息
            skuStockService.remove(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId,productSku.getId()));
        });
        //根据商品id删除图片详情信息
        productDetailsMapper.delete(new LambdaQueryWrapper<ProductDetails>().in(ProductDetails::getProductId,ids));

    }

    @Override
    public void updateAuditStatusById(Long id, Integer auditStatus) {
        //创建一个空对象
        Product product = new Product();
        //设置主键
        product.setId(id);
        product.setAuditStatus(auditStatus);
        //判断
        if (auditStatus==1){
            product.setAuditMessage("审核通过");
        }else if (auditStatus==-1){
            product.setAuditMessage("审核驳回");
        }else {
            throw new ServiceException("审核状态值非法");
        }
        baseMapper.updateById(product);
    }

    @Override
    public void getStatusById(Long id, Integer status) {
        //创建一个空对象
        Product product = new Product();
        //设置主键
        product.setId(id);
        //设置商品的状态
        product.setStatus(status);
        //自带的方法设置商品状态
        baseMapper.updateById(product);
        //根据商品id设置sku的状态
       // productSkuService.update(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId,id));

        //根据商品id遍历获取商品sku的id集合
        List<ProductSku> productSkuList = productSkuService.list(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
        productSkuList.forEach(productSku -> {

            if (status==1){
            //获取布隆过滤器
            RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter("sku:bloom:filter");
            bloomFilter.add(productSku.getId());
            //判断status是否等于1,1为上架,将商品skuId添加到布隆过滤器里面
            }
            productSku.setStatus(status);
            productSkuService.updateById(productSku);
            skuStockService.update(new LambdaUpdateWrapper<SkuStock>().eq(SkuStock::getSkuId,productSku.getId()).set(SkuStock::getStatus,status));

        });

    }

    @Override
    public List<ProductSku> getTopSale() {
        return productSkuMapper.selectTopSale();
    }

    @Override
    public List<ProductSku> getProducctSkuList(SkuQuery skuQuery) {
        return baseMapper.getProducctSkuList(skuQuery);
    }


    //获取商品sku最新价格信息
    @Override
    public SkuPriceVo getSkuPrice(Long skuId) {

        //调用自带的方法获取ProductSku信息
        ProductSku productSku = productSkuService.getById(skuId);
        //创建SkuPriceVo对象
        SkuPriceVo skuPriceVo = new SkuPriceVo();
        //设置属性值
        skuPriceVo.setSkuId(skuId);
        skuPriceVo.setSalePrice(productSku.getSalePrice());
        skuPriceVo.setMarketPrice(productSku.getMarketPrice());
        return skuPriceVo;
    }

    @SpzxCache(prefix = "productDetails")
    @Override
    public ProductDetails getProductDetails(Long id) {
        return productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>()
                        .eq(ProductDetails::getProductId, id)
        );
    }

    @SpzxCache(prefix = "skuSpecValue:")
    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>()
                        .eq(ProductSku::getProductId, id)
                        .select(ProductSku::getId, ProductSku::getSkuSpec));
        Map<String,Long> skuSpecValueMap = new HashMap<>();
        productSkuList.forEach(item -> {
            skuSpecValueMap.put(item.getSkuSpec(), item.getId());
        });
        return skuSpecValueMap;
    }

    @Override
    public SkuStockVo getSkuStock(Long skuId) {
        SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>()
                        .eq(SkuStock::getSkuId, skuId)
                        .select(SkuStock::getAvailableNum, SkuStock::getSaleNum));
        SkuStockVo skuStockVo = new SkuStockVo();
        BeanUtils.copyProperties(skuStock,skuStockVo);
        return skuStockVo;
    }

    @SpzxCache(prefix = "product:")
    @Override
    public Product getProductInfoById(Long id) {
        return baseMapper.selectById(id);
    }


}
